package com.memory.monitor.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.memory.monitor.common.ErrorCode;
import com.memory.monitor.exception.BusinessException;
import com.memory.monitor.exception.ThrowUtils;
import com.memory.monitor.job.UserExcelListener;
import com.memory.monitor.mapper.UserMapper;
import com.memory.monitor.model.dto.user.UserQueryRequest;
import com.memory.monitor.model.entity.User;
import com.memory.monitor.model.enums.UserRoleEnum;
import com.memory.monitor.model.vo.LoginUserVO;
import com.memory.monitor.model.vo.UserVO;
import com.memory.monitor.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.memory.monitor.constant.ExcelConstant.*;
import static com.memory.monitor.constant.UserConstant.SALT;
import static com.memory.monitor.constant.UserConstant.USER_LOGIN_STATE;
import static com.memory.monitor.job.UserExcelListener.CACHED_DATA_LIST;


/**
 * 用户服务实现
 *
 * @author <a href="http://deng-2022.atomgit.net/blog/">Memory</a>
 * @from <a href="https://gitee.com/deng-2022">deng-2022</a>
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        // 密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        }
        synchronized (userAccount.intern()) {
            // 账户不能重复
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_account", userAccount);
            long count = this.baseMapper.selectCount(queryWrapper);
            if (count > 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
            }
            // 2. 加密
            String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
            // 3. 插入数据
            User user = new User();
            user.setUserAccount(userAccount);
            user.setUserPassword(encryptPassword);
            boolean saveResult = this.save(user);
            if (!saveResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
            }
            return user.getId();
        }
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
        }
        // 2. 加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account", userAccount);
        queryWrapper.eq("user_password", encryptPassword);
        User user = this.getOne(queryWrapper);
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return currentUser;
    }

    /**
     * 获取当前登录用户（允许未登录）
     *
     * @param request
     * @return
     */
    @Override
    public User getLoginUserPermitNull(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            return null;
        }
        // 从数据库查询（追求性能的话可以注释，直接走缓存）
        long userId = currentUser.getId();
        return this.getById(userId);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    @Override
    public boolean isAdmin(HttpServletRequest request) {
        // 仅管理员可查询
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        return isAdmin(user);
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    /**
     * 用户注销
     *
     * @param request
     */
    @Override
    public boolean userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute(USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVO(List<User> userList) {
        if (CollectionUtils.isEmpty(userList)) {
            return new ArrayList<>();
        }

        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public Page<UserVO> getUserVO(Page<User> userPage) {
        List<User> userList = userPage.getRecords();
        List<UserVO> userVOList = this.getUserVO(userList);

        Page<UserVO> userVOPage = new Page<>();
        return userVOPage.setRecords(userVOList);
    }

    /**
     * 分页查询用户列表(已脱敏)
     *
     * @param userQueryRequest userQueryRequest 查询参数
     * @return 用户列表(已脱敏)
     */
    @Override
    public Page<UserVO> listUserByPage(UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = this.page(new Page<>(current, size));

        QueryWrapper<User> queryWrapper = this.getQueryWrapper(userQueryRequest);
        return getUserVO(this.page(userPage, queryWrapper));
    }

    /**
     * 获取用户列表
     */
    @Override
    public List<UserVO> listUserByPage() {
        return getUserVO(this.list());
    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {

        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }

        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        String company = userQueryRequest.getCompany();
        String dept = userQueryRequest.getDept();
        String job = userQueryRequest.getJob();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(userAccount), "user_account", userAccount);
        queryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "user_role", userRole);
        queryWrapper.like(StringUtils.isNotBlank(company), "company", company);
        queryWrapper.like(StringUtils.isNotBlank(dept), "dept", dept);
        queryWrapper.like(StringUtils.isNotBlank(job), "job", job);

        return queryWrapper;
    }

    @Override
    public Boolean readExcel(MultipartFile multipartFile) {
        // 1.转换文件为字节流
        InputStream inputStream;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 2.执行文件处理逻辑
        EasyExcel.read(inputStream, User.class, new UserExcelListener()).sheet().doRead();
        // 3.入库
        boolean saveBatch = this.saveBatch(CACHED_DATA_LIST);
        ThrowUtils.throwIf(!saveBatch, ErrorCode.PARAMS_ERROR);
        return true;
    }

    @Override
    public Boolean writeExcel(String path) {
        // 1.定义文件路径
        String fullPath = DOWNLOAD_PATH + USER_TABLE_NAME;
        // 2.检查文件是否存在
        this.isExist(fullPath);
        // 3.根据路径导出
        List<UserVO> userList = this.listUserByPage();
        EasyExcel.write(fullPath, User.class).sheet(USER_SHEET_NAME).doWrite(userList);

        return true;
    }

    /**
     * 检查文件是否存在
     *
     * @param fullPath
     */
    public void isExist(String fullPath) {
        File file = new File(fullPath);
        if (file.exists()) {
            // 文件存在，则删除
            boolean isDeleted = file.delete();
            if (!isDeleted) {
                // 删除文件失败的处理
                throw new RuntimeException("删除文件失败: " + fullPath);
            }
            // 可以在这里添加日志或其他操作，表明文件已被删除
            System.out.println("文件已成功删除: " + fullPath);
        }

        // 文件不存在或已被删除，则尝试创建其父目录
        File parentDir = file.getParentFile();
        if (!parentDir.exists() && !parentDir.mkdirs()) {
            // 创建目录失败的处理
            throw new RuntimeException("创建父级目录失败: " + parentDir.getAbsolutePath());
        }
        // 只有在成功创建目录（或目录已存在）时才打印日志
        if (parentDir.exists()) {
            // 可以在这里添加日志或其他操作，表明目录已存在或已被创建
            System.out.println("父级目录已存在或已成功创建: " + parentDir.getAbsolutePath());
        }
    }
}
